<?php

namespace App\Http\Controllers\Agent;

use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Models\WithDraw;
use App\Models\WithdrawAccount;
use App\Models\GuildUserComm;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Service\ApiService;
use Illuminate\Pagination\LengthAwarePaginator;

class DrawController extends Controller
{
	 public $v = 'agent.draw.';
	 
	 public $paginate = 15;

    /**
     * 提现记录
     * @param Request $request
     * @return type
     */
    public function index(Request $request){
		$gid = Auth::guard('agent')->user()->gid;
        $stime = trim($request->query('stime'));
		$etime = trim($request->query('etime'));
		$status = trim($request->query('status'));
		
		$builder = new WithDraw();
		$query =  $builder->with(['drawaccount'=>function($query){
				$query->select('guser_id', 'name', 'alipay');
			}])
			->when($status, function ($query) use ($status) {
				$newstatus = $status == 3 ? 0 : $status;
				return $query->where('status', $newstatus);
			});
		if(!empty($stime) && !empty($etime)) {
			$etimes = $etime.' 23:59:59';
			$query = $query->whereBetween('created_at', [$stime, $etimes]);
		}
		$draw = $query->where('gid', $gid)->orderBy('id', 'desc')->paginate($this->paginate);
        return view($this->v . 'index', compact('stime', 'etime', 'status', 'draw'));
    }
	/**
     * 收益提现
     * @param Request $request
     * @return type
     */
	public function commission(){
		$gid = Auth::guard('agent')->user()->gid;
		$id = Auth::guard('agent')->user()->id;
		$comm = GuildUserComm::where(['gid' => $gid, 'guser_id' => $id])->select('balance', 'total_money')->first();
		return view($this->v . 'commission', compact('comm'));
	}
	/**
     * 提现账户
     * @param Request $request
     * @return type
     */
	public function accountlist(){
		$gid = Auth::guard('agent')->user()->gid;
		$id = Auth::guard('agent')->user()->id;
		$account = WithdrawAccount::where(['gid' => $gid, 'guser_id' => $id])->first();
		return view($this->v . 'accountlist', compact('account'));
	}
	/**
     * 提现账户提交
     * @param Request $request
     * @return type
     */
	public function accountcreate(Request $request, WithdrawAccount $withdrawAccountModels){
		$gid = Auth::guard('agent')->user()->gid;
		$guser_id = Auth::guard('agent')->user()->id;
		$params = $request->all();
		$newparams = ['mobile' => $params['mobile'], 'alipay' => $params['alipay'], 'name' => $params['name'], 'alipay_code' => $params['alipay_code']];
		$account = WithdrawAccount::where(['gid' => $gid, 'guser_id' => $guser_id])->first();
		if(!empty($account)) {
			$res = (new \App\Service\DrawService())->upDrawaAccount($newparams, $withdrawAccountModels, $account->id, 1);
		} else {
			$res = (new \App\Service\DrawService())->addDrawaAccount($newparams, $gid, $guser_id);
		}	
		if($res['status'] == -1) {
			return ajaxError($res['error']);
		} elseif($res['status'] == 0) {
			return ajaxError();
		}
		return ajaxSuccess();
	}
	/**
     * 申请提现
     * @param Request $request
     * @return type
     */
    public function applyAdd(GuildUserComm $gUserComm)
    {
        $gid = Auth::guard('agent')->user()->gid;
		$id = Auth::guard('agent')->user()->id;
        $guser = $gUserComm->where(['gid' => $gid, 'guser_id' => $id])->first();
        return view($this->v . 'apply_add', compact('guser'));
    }
    /**
     * 申请提现请求
     * @return type
     */
    public function applySave(Request $request,GuildUserComm $gUserComm,WithDraw $withDraw ){
        $params = $request->all();
        $user = Auth::guard('agent')->user();
		$account = WithdrawAccount::where(['gid' => $user->gid, 'id' => $user->id])->first();
		if(empty($account)) {
			return ajaxError('您还未绑定支付宝,请绑定后在申请提现');
		}
        //提现的金额
        $money = $params['money'];
        try {
            DB::beginTransaction();
            $updateBalance= $gUserComm->where(['gid' => $user->gid, 'guser_id' => $user->id])->decrement('balance', $money);
            //用户支付成功的
            if (!$updateBalance){
                DB::rollBack();
                return ajaxError();
            }
            //增加提现日志记录
            $withDraw->guser_id = $user->id;
			$withDraw->gid = $user->gid;
            $withDraw->money = $money;
			$withDraw->created_at = date('Y-m-d H:i:s');
            $insert = $withDraw->save();
            if (!$insert){
                DB::rollBack();
                return ajaxError();
            }
            DB::commit();
        } catch (LogicException $e) {
            DB::rollBack();
        }
        return ajaxWin("提现成功");
    }    
}
